package com.maodou.touchtransferpc.runner;

import cn.hutool.log.dialect.slf4j.Slf4jLog;
import com.maodou.touchtransferpc.util.Config;
import com.maodou.touchtransferpc.util.QRCodeUtil;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.net.*;
import java.util.Enumeration;

/**
 * @Description 启动socketServer
 * @Author Wang Yucui
 * @Date 9/3/2020 11:38 AM
 */
@Component
public class SocketServerRunner implements ApplicationRunner {

    private int port = 19999;
    private static Slf4jLog log = new Slf4jLog("SocketServerRunner");

    @Override
    public void run(ApplicationArguments var1) throws Exception {
        socketThreat();
    }

    /**
     * @Description socket服务端，将本机ip地址返回给客户端
     * @author Wang Yucui
     * @date 9/3/2020 11:42 AM
     */
    private void socketThreat() {
        new Thread(() -> {
            while (true) {
                try {
                    DatagramSocket socket = new DatagramSocket(port);
                    byte[] buffer = new byte[255];
                    DatagramPacket receivePacket = new DatagramPacket(buffer, 0, buffer.length);
                    log.info("准备接收数据");
                    socket.receive(receivePacket);
                    String clientAddress = receivePacket.getAddress().getHostAddress();
                    String clientUniqueCode = new String(receivePacket.getData(), 0, receivePacket.getLength());
                    log.info("服务器接收到的唯一识别码是: " + clientUniqueCode);

                    String serverUniqueCode = Config.getServerUniqueCode();
                    if (serverUniqueCode.equals(clientUniqueCode)) {
//                        // 回复数据--本机ip地址
                        // 本机IP地址是根据 发过来的socket包确定的
                        String hostAddress = getLocalAddress(clientAddress);
                        DatagramPacket replypacket = new DatagramPacket(hostAddress.getBytes(),
                                hostAddress.getBytes().length, receivePacket.getAddress(), receivePacket.getPort());
                        socket.send(replypacket);
                    }
                    socket.close();
                } catch (Exception e) {

                }

            }

        }).start();
    }

    private String getLocalAddress(String clientIp){
        log.info("Client IP:" + clientIp);
        if (clientIp == null || !clientIp.contains(".")) {
            return "";
        }

        String clientHead = clientIp.split("\\.")[0];
        log.info("Client HEAD:" + clientHead);

        try{
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()){
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()){
                    InetAddress ip = (InetAddress) addresses.nextElement();
                    String ipStr = ip.getHostAddress();
                    log.info("ip: " + ipStr);
                    if (ipStr.startsWith(clientHead)){
                        log.info("本机的IP = " + ip.getHostAddress());
                        return ipStr;
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return "";
    }
}